#pragma once

#include "graph/Util.h"
#include "EventHandler.h"

class PaintEventHandler : public EventHandler
{
public:
	BEGIN_DEFINE_CLASS(CLASSID_NULL)
		USE_INTERFACE_ENTRY(EventHandler)
	END_DEFINE_CLASS()

	PaintEventHandler(){}
	virtual ~PaintEventHandler()
	{
	}

	virtual void EventLoopBegin()
	{
		__super::EventLoopBegin();
	}
	virtual void EventLoopEnd()
	{
		Trackers::iterator itbegin = m_trackers.begin();
		Trackers::iterator itend = m_trackers.end();
		for (; itbegin != itend; ++itbegin)
			delete *itbegin;
		m_trackers.clear();
	}
	virtual void Draw()
	{
		Trackers::iterator itbegin = m_trackers.begin();
		Trackers::iterator itend = m_trackers.end();
		for (; itbegin != itend; ++itbegin)
		{
			Tracker* tracker  = *itbegin;
			tracker->Draw();
		}
	}

protected:
	virtual bool OnLButtonUp(SystemEventArgs* e)
	{
		if (m_trackers.size()  == 0u)
			return false;

		Tracker* activeTracker = m_trackers[m_trackers.size()-1];
		 bool result = EndTrack(e,activeTracker->BeginPoint(),activeTracker->EndPoint());
		 m_trackers.erase(m_trackers.begin()+m_trackers.size()-1);
		 delete activeTracker;
		 return result;
	}

	virtual bool OnLButtonDown(SystemEventArgs* e)
	{
		Tracker* tracker = BeginTrack();
		if (!tracker)
			return false;
		m_trackers.push_back(tracker);

		Trackers::iterator itbegin = m_trackers.begin();
		Trackers::iterator itend = m_trackers.end();
		for (; itbegin != itend; ++itbegin)
		{
			Tracker* tracker  = *itbegin;
			tracker->Track(graphics,e->GetLocation());
		}
		return true;
	}
	virtual bool OnMouseMove(SystemEventArgs* e)
	{
		Trackers::iterator itbegin = m_trackers.begin();
		Trackers::iterator itend = m_trackers.end();
		for (; itbegin != itend; ++itbegin)
		{
			Tracker* tracker  = *itbegin;
			tracker->Tracking(e->GetLocation());
		}
		return true;
	}

protected:
	virtual Tracker* BeginTrack() = 0;
	virtual bool EndTrack(SystemEventArgs* e,const Point& begin,const Point& end) = 0;

private:
	Trackers m_trackers;
};